package com.fpt.mockproject.j21.absd.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Su dung de ma hoa string -> ma hash MD5
 * EXAMPLE :
 *   String origin = "Linh Dep Trai";
 *   MD5_Hashing md5 = new MD5_Hashing(origin);
 *   String encrypted = md5.encrypt();
 *   // encrypted => la ma md5 cua chuoi "Linh Dep Trai"
 * @author Linh HB Breaker
 *
 */
public class MD5_Hashing {
	
	private String original;
	
	public MD5_Hashing(String original) {
		this.original = original;
	}
	
	/**
	 * NO NEED TO USE => NO NEED TO KNOW
	 * @param digest
	 * @return
	 */
	public static String byteArrayToHexString(byte[] digest)
	{
		StringBuffer sb = new StringBuffer();
		for (byte b : digest) {
			String hex = Integer.toHexString((int) (b & 0xff));
			if(hex.length() == 1)
				sb.append('0');
			sb.append(hex);
		}
		return sb.toString();
	}
	
	/**
	 * Important, just use this only
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public String encrypt() throws NoSuchAlgorithmException
	{
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(this.original.getBytes());
		byte[] digest = md.digest();

		return byteArrayToHexString(digest);
	}
	
	/**
	 * Chuyen ma md5 sang dang byte
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public byte[] encryptToByte() throws NoSuchAlgorithmException
	{
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(this.original.getBytes());
		return md.digest();
	}
}
